package org.ns.summer.mvc.fuzzysearch;

/**
 * 前缀模糊查询
 */
public class FuzzySearch <T>{

    private SearchNode root = new SearchNode(' ');

    public T add(String text, T value) {
        SearchNode node = root;
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            node = node.getNextOrCreate(c);
        }
        T old = (T)node.getValue();
        node.setValue(value);
        return old;
    }

    public T match(String text) {
        SearchNode node = root;
        SearchNode allNode = null;
        int allNodeIndex = -1;
        for (int i = 0; i < text.length(); i++) {
            char c = text.charAt(i);
            node = node.getNext(c);
            if (node == null) {
                if (allNodeIndex != -1) {
                    node = allNode;
                    i = allNodeIndex + 1;
                } else {
                    break;
                }
            } else if (node.isAll() && allNode == null) {
                allNode = node;
                allNodeIndex = i;
            }
        }
        if (node == null) {
            return null;
        } else {
            return (T)node.getValue();
        }
    }

    public static void main(String[] args) {
        FuzzySearch<String> search = new FuzzySearch<>();
        search.add("/1234/ewew*", "dddd");
        search.add("/1234/ewe*.jsp", "cccc");
        System.out.println(search.match("/1234/ewew"));
        System.out.println(search.match("/1234/ewe3.jsp"));
        System.out.println(search.match("/1234/ewew"));
    }
}
